package map.android.baidu.carpool.page.usercenter;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.api.ComAPIManager;
import com.baidu.mapframework.component.ComConstant;
import com.baidu.mapframework.widget.MToast;
import map.android.baidu.carpool.Config;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.UserCenterData;
import map.android.baidu.carpool.model.URLModel;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.UserCenterResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.CarpoolAlertDialog;
import map.android.baidu.carpool.utils.SafeUtils;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.utils.ToastForCarpool;

/**
 * 个人中心页面
 * 
 * @author zhangtongyu
 * 
 */
public class UserCenterPage extends CarpoolBasePage implements OnClickListener {
    public final static String TAG = "UserCenterPage";

    private Context mContext;
    private LayoutInflater mInflater;
    private Resources mRes;

    private View mView;
    private TitleHelpler mTitleHelper;

    private RelativeLayout mOrderListRel;
    private RelativeLayout mUserInfoRel;
    private RelativeLayout mDiscountRel;
    private RelativeLayout mInviteCodeRel;
    private RelativeLayout mNoticeRel;
    private RelativeLayout mInsuranceRel;
    private RelativeLayout mCallServiceRel;
    private RelativeLayout mAddShortCutRel;

    private TextView mOrderTagTv;
    private TextView mUserInfoCompleteTv;
    private TextView mDiscountTagTv;
    private TextView mServiePhoneNumTv;

    private Bundle mBundle;
    private String mCallServiceStr;
    private UserCenterResponse mUserCenterResponse;
    private IDataStatusChangedListener<UserCenterResponse> listener = new IDataStatusChangedListener<UserCenterResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<UserCenterResponse> data, UserCenterResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    mUserCenterResponse = response;
                    updateUI(response);
                    showLoadingDialog(false);
                } else {
                    MToast.show(mContext, "网络连接异常，请检查网络");
                    showLoadingDialog(false);
                }
            } else {
                showLoadingDialog(false);
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = APIProxy.res().getBaseActivity();
        mInflater = APIProxy.res().getInflater();
        mRes = APIProxy.res().getResources();
        if (CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity()) != null) {
            mCallServiceStr = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity()).data.customerServicePhone;
        }
        if (mView == null) {
            mView = APIProxy.res().inflate(R.layout.layout_page_user_center, container, false);
            initView();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }

        requestUserCenterData();
        return mView;
    }

    private void requestUserCenterData() {
        UserCenterData userCenterData = new UserCenterData(mContext);
        userCenterData.post(listener);
    }

    private void initView() {

        initTitleBar();
        mOrderListRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_order_center_layout);
        mUserInfoRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_center_userinfo_layout);
        mDiscountRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_center_discount_layout);
        mInviteCodeRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_invite_code_layout);
        mNoticeRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_center_bottom_notice_layout);
        mInsuranceRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_insurance_layout);
        mCallServiceRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_call_service_layout);
        mAddShortCutRel = (RelativeLayout) mView.findViewById(R.id.carpool_usercenter_add_shortcut_layout);

        mOrderTagTv = (TextView) mView.findViewById(R.id.carpool_usercenter_order_center_tag);
        mUserInfoCompleteTv = (TextView) mView.findViewById(R.id.carpool_usercenter_userinfo_desc_tv);
        mDiscountTagTv = (TextView) mView.findViewById(R.id.carpool_usercenter_discount_desc_tv);
        mServiePhoneNumTv = (TextView) mView.findViewById(R.id.carpool_usercenter_call_service_num_tv);

        mOrderListRel.setOnClickListener(this);
        mUserInfoRel.setOnClickListener(this);
        mDiscountRel.setOnClickListener(this);
        mInviteCodeRel.setOnClickListener(this);
        mNoticeRel.setOnClickListener(this);
        mInsuranceRel.setOnClickListener(this);
        mCallServiceRel.setOnClickListener(this);
        mAddShortCutRel.setOnClickListener(this);

    }

    private void initTitleBar() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(new OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
        mTitleHelper.setCenterView("个人中心");
    }

    private void updateUI(UserCenterResponse response) {
        if (SafeUtils.safeString2int(response.data.unFinishedOrderNum) == 0) {
            mOrderTagTv.setVisibility(View.GONE);
        } else {
            mOrderTagTv.setVisibility(View.VISIBLE);
            mOrderTagTv.setText("未完成" + response.data.unFinishedOrderNum);
        }
        if ("".equals(response.data.userInfo.userPic)) {
            mUserInfoCompleteTv.setVisibility(View.VISIBLE);
        } else {
            mUserInfoCompleteTv.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(response.data.discountDesc)) {
            mDiscountTagTv.setVisibility(View.VISIBLE);
            mDiscountTagTv.setText(response.data.discountDesc);
        } else {
            mDiscountTagTv.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mCallServiceStr)) {
            mServiePhoneNumTv.setVisibility(View.VISIBLE);
            mServiePhoneNumTv.setText(mCallServiceStr);
        } else {
            mServiePhoneNumTv.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(response.data.showInvitationCode)) {
            mInviteCodeRel.setVisibility(View.GONE);
        } else {
            mInviteCodeRel.setVisibility(View.VISIBLE);
        }

        mBundle = new Bundle();
        mBundle.putSerializable(UserCenterResponse.UserInfoSimple.class.getName(), response.data.userInfo);
    }


    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.carpool_usercenter_order_center_layout:
                // 去订单列表
                APIProxy.navi().navigateTo(OrderListPage.class, null);
                break;
            case R.id.carpool_usercenter_center_userinfo_layout:
                // 去我的资料
                if (mBundle == null) {
                    return;
                }
                APIProxy.navi().navigateTo(UserInfoPage.class, mBundle);
                break;
            case R.id.carpool_usercenter_center_discount_layout:
                // 去优惠列表
                Bundle bundle = new Bundle();
                bundle.putString("from", this.getClass().getName());
                showLoadingDialog(true);
                APIProxy.navi().navigateTo(DiscountListPage.class, null);
                break;
            case R.id.carpool_usercenter_invite_code_layout:
                // 去邀请码页面
                if(Config.MONKEY_OPEN){
                    return;
                }
                if (mUserCenterResponse != null && mUserCenterResponse.data != null && !TextUtils.isEmpty(mUserCenterResponse.data.showInvitationCode)) {
                    UserInfoSetting.goToWebShell(mUserCenterResponse.data.showInvitationCode + "&os=android", "邀请码");
                }
                break;
            case R.id.carpool_usercenter_center_bottom_notice_layout:
                // 去使用说明
                UserInfoSetting.goToWebShell(URLModel.USE_NOTICE_URL, "使用说明");
                break;
            case R.id.carpool_usercenter_insurance_layout:
                // 去保险协议
                UserInfoSetting.goToWebShell(URLModel.INSUANCE_URL, "保险协议");
                break;
            case R.id.carpool_usercenter_call_service_layout:
                // 去联系客服
                if(Config.MONKEY_OPEN){
                    return;
                }
                if (CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity()) != null) {
                    MainConfigResponse mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity());
                    if (mainConfigResponse != null && mainConfigResponse.data != null && !TextUtils.isEmpty(mainConfigResponse.data.customerServicePhone)) {
                        callService(mainConfigResponse.data.customerServicePhone);
                    }
                }
                break;
            case R.id.carpool_usercenter_add_shortcut_layout:
                // 添加到桌面
                addShortcut();
                break;
        }


    }

    private void callService(final String callNum) {
        CarpoolAlertDialog.Builder builder = new CarpoolAlertDialog.Builder(getActivity());
        builder.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //直接结束dialog
            }
        });
        builder.setPositiveButton("拨打电话", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ComAPIManager.getComAPIManager().getSystemAPI().dial(callNum);
            }
        });
        builder.setTitle("确认拨打电话" + callNum);
        builder.create().show();
    }

    private void addShortcut() {
//           APIProxy.settings().addShortcut("carpool", "百度顺风车",
//                   ComAPIManager.getComAPIManager().getResourceAPI(getComId()).getBaseDrawableId("R.drawable.ic_pinche_launcher"));
        ToastForCarpool.show(mContext, "快捷方式已添加");
        APIProxy.settings().addShortcut("carpool", "百度顺风车",
                ComConstant.RESOURCES.PINCHE_SHORTCUT_RESOURCE_ID);
    }
}